package com.base.pub.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionIdListener;
import javax.servlet.http.HttpSessionListener;

import org.dragonnova.business.cache.EhCacheBean;
import org.dragonnova.business.common.Constants;
import org.dragonnova.business.message.mq.kafka.KafkaMessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.base.pub.util.DateUtils;

public class SessionFilter implements Filter {

	private final static Logger LOGGER = LoggerFactory
			.getLogger(SessionFilter.class);

	private FilterConfig filterConfig;

	@Autowired
	private EhCacheBean ehCache;
	@Autowired
	private KafkaMessageListener kafkaMessageListener;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

		this.filterConfig = filterConfig;
		this.filterConfig.getServletContext().addListener(
				new HttpSessionIdListener() {

					@Override
					public void sessionIdChanged(HttpSessionEvent event,
							String oldSessionId) {
						LOGGER.debug("sessionId \'"
								+ event.getSession().getId()
								+ " \' changed when:"
								+ DateUtils.getTimes(event.getSession()
										.getCreationTime(),
										DateUtils.FORMAT_DATE_1));
					}

				});
		this.filterConfig.getServletContext().addListener(
				new HttpSessionListener() {

					@Override
					public void sessionDestroyed(HttpSessionEvent se) {
						HttpSession session = se.getSession();

						ehCache.remove(Constants.USER_CACHE_NAME,
								session.getId());

						LOGGER.debug("sessionId \'"
								+ session.getId()
								+ " \' destroyed when:"
								+ DateUtils.getTimes(session.getCreationTime(),
										DateUtils.FORMAT_DATE_1));
					}

					@Override
					public void sessionCreated(HttpSessionEvent se) {
						HttpSession session = se.getSession();

						// TODO 日志记录
						LOGGER.debug("sessionId \'"
								+ session.getId()
								+ "\' created when:"
								+ DateUtils.getTimes(session.getCreationTime(),
										DateUtils.FORMAT_DATE_1));

					}
				});

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

}
